package cn.lamplet.util.kccu;

import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;


public class ParsePara {

    private final Logger logger = LoggerFactory.getLogger(ParsePara.class);

    ArrayList<Integer> paraList;
    private String dir;
    private String paraFileName;

    public ParsePara(String dir, String paraFileName) {
        this.dir = dir;
        this.paraFileName = paraFileName;
        paraList = new ArrayList<>();
    }
    public ParsePara(InputStream inputStream) {
        this.paraList = new ArrayList<>();
        try {
            List<String> lines = IOUtils.readLines(inputStream, StandardCharsets.UTF_8);
            for (String line : lines) {
                handleLine(line);
            }
        } catch (Exception e) {
            logger.error("解析par文件异常", e);
        }
    }

    public ParsePara() {
        paraList = new ArrayList<>();
    }

    public void handlePara() {
        File file = new File(dir, paraFileName);
        String line;
        int ret;
        BufferedReader reader = null;
        try {
            reader = new BufferedReader(new FileReader(file));
            while ((line = reader.readLine()) != null) {
                handleLine(line);

            }
        } catch (Exception e) {
            System.out.println(e.getStackTrace());
        } finally {
            try {
                reader.close();
            } catch (Exception e) {
                e.printStackTrace();
            }

        }
    }

    private void  handleLine(String line) {
        if (line.charAt(0) == '#') return;
        String[] str = line.split(";");
        for (int i = 1; i < str.length; i += 2) {
            if (str[i].equals("#")) {
                break;
            }
            //        System.out.println(str[i].substring(2) + ":" + str[i + 1]);

            int i1 = Integer.parseInt(str[i].substring(2), 16) >> 16;
            paraList.add(i1);
            int i2 = Integer.parseInt(str[i + 1], 10);
            paraList.add(i2);
            //System.out.printf("0x%x  0x%x\n", i1, i2);
        }

    }

    public ArrayList<Integer> getParaList() {
        handlePara();
        return paraList;
    }

}
